package com.abss.vote.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.log4j.Logger;

/**
 * 微信相关工具
 */
public class MPUtils {
    //用log4j 创建一个log对象
    private static Logger logger = Logger.getLogger(MPUtils.class);

    /**
     * 创建小程序码
     */
    private static String WX_CREATE_QRCODE_URL="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";

    public static String getActivityQRCode(String activityId, String bizCode, String accessToken) {
        String url = WX_CREATE_QRCODE_URL + accessToken;
        byte[] ret = getMPCodeImageData(url, activityId + "_" + bizCode,
                "start/pages/activity_details/activity_details", true);

        if (ret == null || ret.length < 1000) {
            logger.info("失败：" + ret);
            return "";
        }
        String img_url = OSSUtils.uploadFile(ret,
                "reading/qrcode/activity/" + System.currentTimeMillis() + ".png");
        return img_url;
    }
    
    /**
     * 生成圆形小程序码
     * 
     * @param url
     * @param scene
     * @param page
     * @param isHyaline
     * @return
     */
    private static byte[] getMPCodeImageData(String url, String scene, String page, boolean isHyaline) {
        byte[] result = null;
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStream stream = null;
        try {
            URL uri = new URL(url);
            conn = (HttpURLConnection) uri.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            out = conn.getOutputStream();
            String path = "{\"scene\":\"" + scene + "\",\"is_hyaline\":true,\"check_path\":false}";
            if (page == null || "".equals(page)) {
                path = "{\"scene\":\"" + scene + "\",\"is_hyaline\":true,\"check_path\":false}";
            } else {
                if (isHyaline) {
                    path = "{\"scene\":\"" + scene + "\",\"page\":\"" + page
                            + "\",\"is_hyaline\":true,\"check_path\":false}";
                } else {
                    path = "{\"scene\":\"" + scene + "\",\"page\":\"" + page + "\",\"check_path\":false}";
                }
            }
            logger.info("url:" + url);
            logger.info("path:" + path);
            out.write(path.getBytes());
            conn.connect();
            stream = conn.getInputStream();
            byte[] buf = new byte[1024 * 1024];
            int len = -1;
            int readcount = 0;
            while ((len = stream.read(buf, readcount, buf.length - readcount)) != -1) {
                readcount += len;
            }
            result = new byte[readcount];
            System.arraycopy(buf, 0, result, 0, readcount);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("生成失败，原因是：" + e.getLocalizedMessage());
        } finally {
            try {
                if (null != stream) {
                    stream.close();
                }
                if (null != out) {
                    out.flush();
                    out.close();
                }
                if (null != conn) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
